package com.gome.axwl.aoc.facade.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageInfo;
import com.gome.axwl.aoc.common.util.BeanJsonUtil;
import com.gome.axwl.aoc.common.util.CollectionUtil;
import com.gome.axwl.aoc.common.util.DateUtil;
import com.gome.axwl.aoc.entity.driver.CarrierFromMasterDto;
import com.gome.axwl.aoc.entity.driver.DriverAccount;
import com.gome.axwl.aoc.entity.driver.DriverIntegrationParamForOcsDto;
import com.gome.axwl.aoc.entity.driver.DriverWithCarrierDto;
import com.gome.axwl.aoc.entity.dto.DriverEvaluationDataFromOrderDto;
import com.gome.axwl.aoc.entity.dto.DriverIntegrationDto;
import com.gome.axwl.aoc.entity.dto.DriverIntegrationFromOrderDto;
import com.gome.axwl.aoc.entity.dto.DriverIntegrationParamDto;
import com.gome.axwl.aoc.entity.dto.GradeRuleDto;
import com.gome.axwl.aoc.entity.dto.IntegrationRuleDto;
import com.gome.axwl.aoc.entity.dto.PageResultDto;
import com.gome.axwl.aoc.entity.dto.QueryResultAndModifyStatusDto;
import com.gome.axwl.aoc.entity.po.DriverIntegrationParamPo;
import com.gome.axwl.aoc.entity.po.DriverIntegrationPo;
import com.gome.axwl.aoc.facade.DriverIntegrationFacade;
import com.gome.axwl.aoc.service.DriverIntegrationService;
import com.gome.axwl.aoc.service.GradeRuleService;
import com.gome.axwl.aoc.service.IntegrationRuleService;
import com.gome.axwl.aoc.service.feign.MasterDataFeignClient;
import com.gome.commons.core.ErrorCode;
import com.gome.commons.core.ResultData;

/**
 * @Description: 司机积分facade实现类
 * @Auther: yinyuxin@gome.com.cn
 * @Date: 2018/4/28 13:59
 */
@Service("driverIntegrationFacade")
public class DriverIntegerationFacadeImpl implements DriverIntegrationFacade {

    private static final Logger LOGGER=LoggerFactory.getLogger(DriverIntegerationFacadeImpl.class);

    @Autowired
    private DriverIntegrationService driverIntegrationService;


    @Autowired
    private MasterDataFeignClient masterDataFeignClient;

    @Autowired
    private IntegrationRuleService integrationRuleService;

    @Autowired
    private GradeRuleService gradeRuleService;



    @Override
    public ResultData<PageResultDto<DriverIntegrationDto>> queryAllDriverIntegration(DriverIntegrationParamDto driverIntegrationParamDto) {
        if (StringUtils.isBlank(driverIntegrationParamDto.getIntegrationDate())){
            String month=DateUtil.date2String(DateUtil.timeCalculation(new Date(),-1,1),DateUtil.FORMAT_DATE_WITHOUT_DAY);
            driverIntegrationParamDto.setIntegrationDate(month);
        }

        //查询数据库
        //加上dc权限
        List<String> carrierNo=new ArrayList<>();
        if (StringUtils.isBlank(driverIntegrationParamDto.getProviderCode())&&StringUtils.isBlank(driverIntegrationParamDto.getDriverCode())){
            if (driverIntegrationParamDto.getDcIds()==null ||"0".equals(driverIntegrationParamDto.getDcIds())){
                return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG,new PageResultDto<>());
            }else {
                ResultData<List<CarrierFromMasterDto>> carrier = masterDataFeignClient.QueryCarrierByKeyword(null, driverIntegrationParamDto.getDcIds());
                if (!Objects.equals(ErrorCode.SUCCESS,carrier.getCode())){
                    return new ResultData<>(ErrorCode.QUERY_FAILOR,"根据dc查询服务商权限失败");
                }
                if (carrier.getData()==null ||carrier.getData().size()<=0){
                    return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG);
                }
                for (CarrierFromMasterDto carrierFromMasterDto:carrier.getData()){
                    carrierNo.add(carrierFromMasterDto.getCarrierNo());
                }
            }
        }
        DriverIntegrationParamPo driverIntegrationParamPo=BeanJsonUtil.beanConvert(driverIntegrationParamDto,DriverIntegrationParamPo.class);
        driverIntegrationParamPo.setProviderCodes(carrierNo);
        PageInfo<DriverIntegrationPo> pageInfo = driverIntegrationService.queryAllDriverIntegration(driverIntegrationParamPo, driverIntegrationParamDto.getPageNum(), driverIntegrationParamDto.getPageSize());
        LOGGER.info("司机积分查询数据库 result{}",BeanJsonUtil.obj2String(pageInfo));
        List<DriverIntegrationDto> driverIntegrationDtosOfResult=BeanJsonUtil.listConvert(pageInfo.getList(),DriverIntegrationDto.class);

        //如果查询的是单个司机，因数据量小，补充 积分生成的补偿机制
        if (!StringUtils.isBlank(driverIntegrationParamDto.getDriverCode())&&(pageInfo.getList()==null||pageInfo.getList().size()==0)){
            ResultData<DriverWithCarrierDto> driverDtailResult = masterDataFeignClient.queryDriverDetail(driverIntegrationParamDto.getDriverCode());
            if (Objects.equals(ErrorCode.SUCCESS,driverDtailResult.getCode())&&driverDtailResult.getData()!=null){
                //masterDataFeignClient.queryDriverDetail这个方法不会返回司机的服务商信息
                List<DriverWithCarrierDto> driverWithCarrierDtos=new ArrayList<>();
                ResultData<PageInfo<DriverWithCarrierDto>> driverWithCarrierResult = masterDataFeignClient.queryDriver(driverDtailResult.getData().getDriverId(), 1, 10);
                if (driverWithCarrierResult!=null &&Objects.equals(ErrorCode.SUCCESS,driverWithCarrierResult.getCode())&&driverWithCarrierResult.getData()!=null&&driverWithCarrierResult.getData().getList()!=null&&driverWithCarrierResult.getData().getList().size()>0){
                    driverWithCarrierDtos.add(driverWithCarrierResult.getData().getList().get(0));
                }
                ResultData resultData = this.createDriversIntegration(driverWithCarrierDtos, driverIntegrationParamDto.getIntegrationDate());
                if (ErrorCode.SUCCESS.equals(resultData.getCode())){
                    LOGGER.info("通过补偿机制新增司机积分记录成功,driverNo{},date{}",driverDtailResult.getData().getDriverNo(), driverIntegrationParamDto.getIntegrationDate());
                }else {
                    LOGGER.info("通过补偿机制新增司机积分记录失败,driverNo{},date{}",driverDtailResult.getData().getDriverNo(), driverIntegrationParamDto.getIntegrationDate());
                }

            }
        }
        if (!CollectionUtils.isEmpty(driverIntegrationDtosOfResult)){
            //拼接司机等级中文
            for (DriverIntegrationDto driverIntegrationDto:driverIntegrationDtosOfResult){
                ResultData<PageInfo<DriverWithCarrierDto>> driversFromMaster = masterDataFeignClient.queryDriver(driverIntegrationDto.getDriverId(), 1,10);
                if (Objects.equals(ErrorCode.SUCCESS,driversFromMaster.getCode())&&!Objects.equals(null,driversFromMaster.getData())&&!CollectionUtils.isEmpty(driversFromMaster.getData().getList())){
                    for (DriverWithCarrierDto driverWithCarrierDto:driversFromMaster.getData().getList()){
                        driverIntegrationDto.setProviderName(driverWithCarrierDto.getCarrier()!=null?driverWithCarrierDto.getCarrier().getCarrierName():driverWithCarrierDto.getCarrierName());
                        driverIntegrationDto.setDriverAccount(driverWithCarrierDto.getContact());
                        driverIntegrationDto.setDirverGradeName(driverIntegrationDto.getDirverGradeId()==0?"未匹配到等级信息":driverIntegrationDto.getDirverGradeName());
                    }
                }
            }
        }
        PageResultDto<DriverIntegrationDto> pageResultDto=new PageResultDto<>();
        pageResultDto.setPageNum(pageInfo.getPageNum());
        pageResultDto.setPageSize(pageInfo.getPageSize());
        pageResultDto.setTotal(pageInfo.getTotal());
        pageResultDto.setPageCount(pageInfo.getPages());
        pageResultDto.setData(driverIntegrationDtosOfResult);
        return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG,pageResultDto);
    }

    @Override
    public ResultData<PageResultDto<DriverIntegrationDto>> queryDriverIntegrationList(String carrierNo, String driverCode, String orderField, Integer orderSort, Integer pageIndex, Integer pageSize) {
        PageInfo<DriverIntegrationPo> pageInfo = driverIntegrationService.queryDriverIntegrationList(carrierNo, driverCode, orderField, orderSort, pageIndex, pageSize);
        List<DriverIntegrationDto> driverIntegrationDtos=BeanJsonUtil.listConvert(pageInfo.getList(),DriverIntegrationDto.class);
        if (!CollectionUtils.isEmpty(driverIntegrationDtos)){
            //拼接司机姓名等信息
            for (DriverIntegrationDto driverIntegrationDto:driverIntegrationDtos){
                ResultData<PageInfo<DriverWithCarrierDto>> driversFromMaster = masterDataFeignClient.queryDriver(driverIntegrationDto.getDriverId(), 1,10);
                if (Objects.equals(ErrorCode.SUCCESS,driversFromMaster.getCode())&&!Objects.equals(null,driversFromMaster.getData())&&!CollectionUtils.isEmpty(driversFromMaster.getData().getList())){
                    for (DriverWithCarrierDto driverWithCarrierDto:driversFromMaster.getData().getList()){
                        driverIntegrationDto.setProviderName(driverWithCarrierDto.getCarrier()!=null?driverWithCarrierDto.getCarrier().getCarrierName():driverWithCarrierDto.getCarrierName());
                        driverIntegrationDto.setDriverAccount(driverWithCarrierDto.getContact());
                        driverIntegrationDto.setDirverGradeName(driverIntegrationDto.getDirverGradeId()==0?"未匹配到等级信息":driverIntegrationDto.getDirverGradeName());
                    }
                }
            }
        }
        PageResultDto<DriverIntegrationDto> pageResultDto=new PageResultDto<>();
        pageResultDto.setPageNum(pageInfo.getPageNum());
        pageResultDto.setPageSize(pageInfo.getPageSize());
        pageResultDto.setTotal(pageInfo.getTotal());
        pageResultDto.setPageCount(pageInfo.getPages());
        pageResultDto.setData(driverIntegrationDtos);
        return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG,pageResultDto);
    }

    @Override
    public ResultData queryDriverTakingsDetail(Integer driverId, String month) {
        return driverIntegrationService.queryDriverTakingsDetail(driverId,month);
    }

    @Override
    @Transactional
    public ResultData   createDriversIntegration(List<DriverWithCarrierDto> drivers,String dateWithoutDay) {
        try {
            if (null == drivers || drivers.size() <= 0) {
                return new ResultData(ErrorCode.SUCCESS, ErrorCode.SUCCESS_MSG);
            }
            if (StringUtils.isBlank(dateWithoutDay)) {
                dateWithoutDay = DateUtil.date2String(DateUtil.timeCalculation(new Date(), -1, 1), DateUtil.FORMAT_DATE_WITHOUT_DAY);
            }
            Map<Integer, DriverWithCarrierDto> driverDataMap = new HashMap<>();
            Integer[] driverIds = new Integer[drivers.size()];
            for (int i = 0; i < drivers.size(); i++) {
                driverIds[i] = drivers.get(i).getDriverId();
                driverDataMap.put(drivers.get(i).getDriverId(), drivers.get(i));
            }
            DriverIntegrationParamForOcsDto driverIntegrationParamForOcsDto = new DriverIntegrationParamForOcsDto();
            driverIntegrationParamForOcsDto.setDriverIds(driverIds);
            driverIntegrationParamForOcsDto.setMonth(dateWithoutDay);
            List<DriverIntegrationFromOrderDto> driverIntegrationFromOrderDtos = this.queryDriversOrderDataFromOcm(driverIntegrationParamForOcsDto, driverDataMap);
            //保存司机积分记录
            if (driverIntegrationFromOrderDtos != null && driverIntegrationFromOrderDtos.size() > 0) {
                //保存数据
                this.insertDriverIntegrations(driverIntegrationFromOrderDtos);
            }
            return new ResultData(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG);
        } catch (Exception e) {
            return new ResultData(ErrorCode.FAILOR,ErrorCode.FAILOR_MSG);
        }

    }


    /**
     * 根据前端在司机积分列表穿的参数，获取该查询的司机列表
     * @param driverIntegrationParamDto
     * @return
     */
    public PageInfo<DriverIntegrationDto> queryDriversOfIntegration(DriverIntegrationParamDto driverIntegrationParamDto){
        PageInfo<DriverIntegrationDto> pageInfo=new PageInfo();
        pageInfo.setPageNum(driverIntegrationParamDto.getPageNum());
        pageInfo.setPageSize(driverIntegrationParamDto.getPageSize());
        List<DriverIntegrationDto> driverIntegrationDtos=new ArrayList<>();
        //1:获取需要查询的司机列表
        if (StringUtils.isBlank(driverIntegrationParamDto.getProviderCode())){
            if (StringUtils.isBlank(driverIntegrationParamDto.getDriverCode())){
                ResultData<PageInfo<DriverWithCarrierDto>> driversFromMaster=new ResultData<>();
                if (driverIntegrationParamDto.getDcNos()!=null &&driverIntegrationParamDto.getDcNos().size()>0){
                    //根据dc来查询司机
                    ResultData<List<DriverAccount>> driversByDcCodes = masterDataFeignClient.getDriversByDcCodes(driverIntegrationParamDto.getDcNos());
                    if (Objects.equals(ErrorCode.SUCCESS,driversByDcCodes.getCode())&&driversByDcCodes.getData()!=null &&driversByDcCodes.getData().size()>0){
                        //进行内存分页
                        PageInfo<DriverWithCarrierDto> pageResultDto = new PageInfo<>();
                        List<DriverWithCarrierDto> driverWithCarrierDtos=BeanJsonUtil.listConvert(driversByDcCodes.getData(),DriverWithCarrierDto.class);
                        Map<String, Object> pagingResultMap = CollectionUtil.getPagingResultMap(driverWithCarrierDtos, driverIntegrationParamDto.getPageNum(), driverIntegrationParamDto.getPageSize());
                        pageResultDto.setPageNum((int) pagingResultMap.get("pageNum"));
                        pageResultDto.setList((List<DriverWithCarrierDto>) pagingResultMap.get("data"));
                        pageResultDto.setTotal(Long.parseLong(pagingResultMap.get("total").toString()));
                        pageResultDto.setPageSize((int) pagingResultMap.get("pageSize"));
                        pageResultDto.setPages((int) pagingResultMap.get("pages"));
                        driversFromMaster.setData(pageResultDto);
                    }
                }
                if (Objects.equals(ErrorCode.SUCCESS,driversFromMaster.getCode())&&!Objects.equals(null,driversFromMaster.getData())&&!CollectionUtils.isEmpty(driversFromMaster.getData().getList())){
                    for (DriverWithCarrierDto driverWithCarrierDto:driversFromMaster.getData().getList()){
                        DriverIntegrationDto driverIntegrationDto=new DriverIntegrationDto();
                        driverIntegrationDto.setDriverId(driverWithCarrierDto.getDriverId());
                        driverIntegrationDtos.add(driverIntegrationDto);
                    }
                    pageInfo.setTotal(driversFromMaster.getData().getTotal());
                    pageInfo.setPages(driversFromMaster.getData().getPages());
                }
            }else {
                //根据司机编码查询司机详情
                ResultData<DriverWithCarrierDto> driversFromMaster3 = masterDataFeignClient.queryDriverDetail(driverIntegrationParamDto.getDriverCode());
                if (Objects.equals(ErrorCode.SUCCESS,driversFromMaster3.getCode())&&!Objects.equals(null,driversFromMaster3.getData())){
                    DriverIntegrationDto driverIntegrationDto=new DriverIntegrationDto();
                    driverIntegrationDto.setDriverId(driversFromMaster3.getData().getDriverId());
                    driverIntegrationDtos.add(driverIntegrationDto);
                }
                pageInfo.setTotal(1);
                pageInfo.setPages(1);
            }
        }else {
            //根据服务商编码查询司机列表
            ResultData<PageInfo<DriverWithCarrierDto>> driversFromMaster2 = masterDataFeignClient.screenDriver(null, null, driverIntegrationParamDto.getProviderCode(), driverIntegrationParamDto.getPageNum(), driverIntegrationParamDto.getPageSize());
            if (Objects.equals(ErrorCode.SUCCESS,driversFromMaster2.getCode())&&!Objects.equals(null,driversFromMaster2.getData())&&!CollectionUtils.isEmpty(driversFromMaster2.getData().getList())){
                for (DriverWithCarrierDto driverWithCarrierDto:driversFromMaster2.getData().getList()){
                    DriverIntegrationDto driverIntegrationDto=new DriverIntegrationDto();
                    driverIntegrationDto.setDriverId(driverWithCarrierDto.getDriverId());
                    driverIntegrationDtos.add(driverIntegrationDto);
                }
                pageInfo.setTotal(driversFromMaster2.getData().getTotal());
                pageInfo.setPages(driversFromMaster2.getData().getPages());
            }
        }
        pageInfo.setList(driverIntegrationDtos);
        return pageInfo;
    }

    /**
     * 调用订单中心拿到司机数据，计算好评率等
     * @param driverIntegrationParamForOcsDto
     * @return
     */
    public List<DriverIntegrationFromOrderDto> queryDriversOrderDataFromOcm(DriverIntegrationParamForOcsDto driverIntegrationParamForOcsDto,Map<Integer,DriverWithCarrierDto> driversDataMap){
        List<DriverIntegrationFromOrderDto> driverIntegrationFromOrderDtos = new ArrayList<>();
        Integer[] driverIds=driverIntegrationParamForOcsDto.getDriverIds();
        String month=driverIntegrationParamForOcsDto.getMonth();
        ResultData<List<DriverEvaluationDataFromOrderDto>> driverEvaluationDataFromOrderDtoResultDatas = driverIntegrationService.queryDriverCounts(driverIntegrationParamForOcsDto);
        if (!Objects.equals(ErrorCode.SUCCESS, driverEvaluationDataFromOrderDtoResultDatas.getCode())) {
            LOGGER.error("生成司机积分等级信息-->调用订单中心查询司机订单汇总数据接口(queryDriverCounts)出现异常,参数:{}", BeanJsonUtil.obj2String(driverIntegrationParamForOcsDto));
            throw new RuntimeException("生成司机积分等级信息-->调用订单中心查询司机订单汇总数据接口(queryDriverCounts)出现异常");
        } else {
            //订单中心没有汇总记录的，运营平台生成该司机默认的积分等级记录
            List<DriverEvaluationDataFromOrderDto>  driverEvaluationDataFromOrderDtos= driverEvaluationDataFromOrderDtoResultDatas.getData();
            if (null==driverEvaluationDataFromOrderDtos){
                for(int i=0;i<driverIds.length;i++){
                    DriverEvaluationDataFromOrderDto driverEvaluationDataFromOrderDto=new DriverEvaluationDataFromOrderDto();
                    driverEvaluationDataFromOrderDto.setDriverId(driverIds[i]);
                    driverEvaluationDataFromOrderDto.setMonth(month);
                    driverEvaluationDataFromOrderDto.setHighPraises(0);
                    driverEvaluationDataFromOrderDto.setOntimeTakings(0);
                    driverEvaluationDataFromOrderDto.setSignPraises(0);
                    driverEvaluationDataFromOrderDto.setSpeechPraise(0);
                    driverEvaluationDataFromOrderDto.setTakingDays(0);
                    driverEvaluationDataFromOrderDto.setTotalDeliverys(0);
                    driverEvaluationDataFromOrderDtos.add(driverEvaluationDataFromOrderDto);
                }
            }else if (driverEvaluationDataFromOrderDtos.size()<driverIds.length){
                List<Integer> driverIdList = Arrays.asList(driverIds);
                List<Integer> driverIdList2=new ArrayList<>(driverIdList);
                for (DriverEvaluationDataFromOrderDto driverEvaluationDataFromOrderDto : driverEvaluationDataFromOrderDtos){
                    if (driverIdList2.contains(driverEvaluationDataFromOrderDto.getDriverId())){
                        driverIdList2.remove(driverEvaluationDataFromOrderDto.getDriverId());
                    }
                }
                for(int i=0;i<driverIdList2.size();i++){
                    DriverEvaluationDataFromOrderDto driverEvaluationDataFromOrderDto=new DriverEvaluationDataFromOrderDto();
                    driverEvaluationDataFromOrderDto.setDriverId(driverIdList2.get(i));
                    driverEvaluationDataFromOrderDto.setMonth(month);
                    driverEvaluationDataFromOrderDto.setHighPraises(0);
                    driverEvaluationDataFromOrderDto.setOntimeTakings(0);
                    driverEvaluationDataFromOrderDto.setSignPraises(0);
                    driverEvaluationDataFromOrderDto.setTakingDays(0);
                    driverEvaluationDataFromOrderDto.setTotalDeliverys(0);
                    driverEvaluationDataFromOrderDto.setSpeechPraise(0);
                    driverEvaluationDataFromOrderDtos.add(driverEvaluationDataFromOrderDto);
                }
            }
            for (DriverEvaluationDataFromOrderDto driverEvaluationDataFromOrderDto : driverEvaluationDataFromOrderDtos) {
                if (null == driverEvaluationDataFromOrderDto) {
                    continue;
                }
                DriverIntegrationFromOrderDto driverIntegrationFromOrderDto = new DriverIntegrationFromOrderDto();
                float favour = 0.00f;
                float ontimeWorkday = 0.00f;
                if (driverEvaluationDataFromOrderDto.getTotalDeliverys()!=null&& driverEvaluationDataFromOrderDto.getTotalDeliverys() != 0 ) {
                    ontimeWorkday = driverEvaluationDataFromOrderDto.getOntimeTakings().floatValue() / driverEvaluationDataFromOrderDto.getTotalDeliverys().floatValue();
                }
                if (driverEvaluationDataFromOrderDto.getSignPraises() !=null && driverEvaluationDataFromOrderDto.getSignPraises()!=0){
                    favour = driverEvaluationDataFromOrderDto.getHighPraises().floatValue() / driverEvaluationDataFromOrderDto.getSignPraises().floatValue();
                }
                driverIntegrationFromOrderDto.setDate(month);
                //准时送达率
                Integer percentDelivery = new BigDecimal(ontimeWorkday).setScale(2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).intValue();
                Integer percentFavour = new BigDecimal(favour).setScale(2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).intValue();
                driverIntegrationFromOrderDto.setDeliveryPercent(percentDelivery);
                driverIntegrationFromOrderDto.setWorkdayPercent(driverEvaluationDataFromOrderDto.getTakingDays());
                driverIntegrationFromOrderDto.setFavourPercent(percentFavour);
                driverIntegrationFromOrderDto.setSignPraises(driverEvaluationDataFromOrderDto.getSignPraises());
                driverIntegrationFromOrderDto.setSpeechPraise(driverEvaluationDataFromOrderDto.getSpeechPraise());
                driverIntegrationFromOrderDto.setDriverId(driverEvaluationDataFromOrderDto.getDriverId());
                DriverWithCarrierDto driverDetail = driversDataMap.get(driverEvaluationDataFromOrderDto.getDriverId());
                if (driverDetail!=null){
                    driverIntegrationFromOrderDto.setDriverCode(driverDetail.getDriverNo());
                    driverIntegrationFromOrderDto.setDriverName(driverDetail.getDriverName());
                    driverIntegrationFromOrderDto.setDriverAccount(driverDetail.getContact());
                    driverIntegrationFromOrderDto.setProviderId(driverDetail.getCarrier() == null ? null : driverDetail.getCarrier().getCarrierId());
                    driverIntegrationFromOrderDto.setProviderCode(driverDetail.getCarrier() == null ? null : driverDetail.getCarrier().getCarrierNo());
                    driverIntegrationFromOrderDto.setProviderName(driverDetail.getCarrier() == null ? null : driverDetail.getCarrier().getCarrierName());
                }
                driverIntegrationFromOrderDtos.add(driverIntegrationFromOrderDto);
            }
        }
        return driverIntegrationFromOrderDtos;
    }


    /**
     * 保存司机积分信息
     *
     * @param driverIntegrationFromOrderDtos
     * @return
     */
    public void insertDriverIntegrations(List<DriverIntegrationFromOrderDto> driverIntegrationFromOrderDtos) {
        List<DriverIntegrationPo> driverIntegrationPosForInsert = new ArrayList<>();
        for (DriverIntegrationFromOrderDto driverIntegrationFromOrderDto : driverIntegrationFromOrderDtos) {
            //校验当前月是否已有该司机的记录
            DriverIntegrationPo driverIntegrationPoNow = driverIntegrationService.queryDriverIntegrationByMonth(driverIntegrationFromOrderDto.getDriverCode(), driverIntegrationFromOrderDto.getProviderCode(), driverIntegrationFromOrderDto.getDate());
            if (null!=driverIntegrationPoNow){
                break;
            }
            //获取上月积分汇总信息
            String dateString = DateUtil.date2String(DateUtil.timeCalculation(DateUtil.string2Date(driverIntegrationFromOrderDto.getDate(), DateUtil.FORMAT_DATE_WITHOUT_DAY), -1, 1), DateUtil.FORMAT_DATE_WITHOUT_DAY);
            DriverIntegrationPo driverIntegrationPo = driverIntegrationService.queryDriverIntegrationByMonth(driverIntegrationFromOrderDto.getDriverCode(), driverIntegrationFromOrderDto.getProviderCode(), dateString);
            DriverIntegrationPo driverIntegrationPo1 = new DriverIntegrationPo();
            driverIntegrationPo1.setIntegrationBase(driverIntegrationPo == null ? 100 : driverIntegrationPo.getIntegrationTotal());
            //保存计算后的积分和等级信息四舍五入为整数
            BigDecimal integrationWorkday = new BigDecimal(this.integrationCalculate(driverIntegrationFromOrderDto.getWorkdayPercent(), 2, driverIntegrationFromOrderDto.getDate())).setScale(1, BigDecimal.ROUND_HALF_UP);
            BigDecimal integrationFavour=new BigDecimal(0);
            BigDecimal integrationDelivery=new BigDecimal(0);
            if (driverIntegrationFromOrderDto.getWorkdayPercent()>0){
                integrationFavour = new BigDecimal(this.integrationCalculate(driverIntegrationFromOrderDto.getFavourPercent(), 0, driverIntegrationFromOrderDto.getDate())).setScale(1, BigDecimal.ROUND_HALF_UP);
                integrationDelivery = new BigDecimal(this.integrationCalculate(driverIntegrationFromOrderDto.getDeliveryPercent(), 1, driverIntegrationFromOrderDto.getDate())).setScale(1, BigDecimal.ROUND_HALF_UP);
            }
            driverIntegrationPo1.setIntegrationFavour(integrationFavour);
            driverIntegrationPo1.setIntegrationWorkday(integrationWorkday);
            driverIntegrationPo1.setIntegrationDelivery(integrationDelivery);
            driverIntegrationPo1.setIntegrationTotal(driverIntegrationPo1.getIntegrationBase() + integrationFavour.add(integrationWorkday).add(integrationDelivery).setScale(0, BigDecimal.ROUND_HALF_UP).intValue());
            driverIntegrationPo1.setDirverGradeId(this.gradeCalculate(driverIntegrationPo1.getIntegrationTotal(), driverIntegrationFromOrderDto.getDate()));
            driverIntegrationPo1.setIntegrationDate(driverIntegrationFromOrderDto.getDate());
            driverIntegrationPo1.setCreateDate(new Date());
            //保存司机服务商信息
            driverIntegrationPo1.setDriverCode(driverIntegrationFromOrderDto.getDriverCode());
            driverIntegrationPo1.setDriverName(driverIntegrationFromOrderDto.getDriverName());

            driverIntegrationPo1.setProviderCode(driverIntegrationFromOrderDto.getProviderCode());
            //保存好评率等
            driverIntegrationPo1.setPercentFavour(driverIntegrationFromOrderDto.getFavourPercent());
            driverIntegrationPo1.setPercentDelivery(driverIntegrationFromOrderDto.getDeliveryPercent());
            driverIntegrationPo1.setWorkday(driverIntegrationFromOrderDto.getWorkdayPercent());
            driverIntegrationPo1.setDriverId(driverIntegrationFromOrderDto.getDriverId());
            driverIntegrationPo1.setSignPraises(driverIntegrationFromOrderDto.getSignPraises());
            driverIntegrationPo1.setSpeechPraise(driverIntegrationFromOrderDto.getSpeechPraise());
            driverIntegrationPosForInsert.add(driverIntegrationPo1);
        }
        if (!CollectionUtils.isEmpty(driverIntegrationPosForInsert)) {
            driverIntegrationService.batchInsert(driverIntegrationPosForInsert);
        }
    }

    /**
     * 通过积分规则结算积分
     * @param dateString
     * @param percentNum
     * @param ruleType 0：好评率  1：准时送达率 2：接单天数
     * @return 积分数
     */
    public  double integrationCalculate(Integer percentNum, Integer ruleType,String dateString){
        //根据时间和类型查询积分规则
        ResultData<QueryResultAndModifyStatusDto<IntegrationRuleDto>> queryResultAndModifyStatusDtoResultData = integrationRuleService.queryIntegrationRulesByType(dateString, ruleType.byteValue());
        if (CollectionUtils.isEmpty(queryResultAndModifyStatusDtoResultData.getData().getData())){
            LOGGER.error("未查询到指定积分规则设置信息，计算积分失败，参数:ruleType={},dateString={}",ruleType,dateString);
            return 0.0;
        }
        for (IntegrationRuleDto integrationRuleDto:queryResultAndModifyStatusDtoResultData.getData().getData()){
            if (percentNum>=integrationRuleDto.getRuleStartNum() && percentNum<=integrationRuleDto.getRuleEndNum()){
                BigDecimal ruleIntegration=integrationRuleDto.getRuleIntegral();
                return integrationRuleDto.getRuleIsAdd()==0?(-ruleIntegration.doubleValue()):ruleIntegration.doubleValue();
            }
        }
        return 0.0;
    }

    /**
     * 通过等级规则添加等级
     * @param dateString
     * @param integratonTotal
     * @return 积分数
     */
    public Integer gradeCalculate(Integer integratonTotal,String dateString){
        //根据时间和类型查询积分规则
        ResultData<QueryResultAndModifyStatusDto<GradeRuleDto>> queryResultAndModifyStatusDtoResultData = gradeRuleService.queryGradeRules(dateString);
        if (CollectionUtils.isEmpty(queryResultAndModifyStatusDtoResultData.getData().getData())){
            LOGGER.error("未查询到指定等级规则设置信息，无法计算等级，参数:,dateString={}",dateString);
            return 0;
        }
        for (GradeRuleDto gradeRuleDto:queryResultAndModifyStatusDtoResultData.getData().getData()){
            if (integratonTotal>=gradeRuleDto.getGradeIntegraStart() && integratonTotal<=gradeRuleDto.getGradeIntegraEnd()){
                return gradeRuleDto.getId();
            }
        }
        return 0;
    }


}
